package chan.project.security;

import chan.project.common.ErrorCode;
import chan.project.exception.BusinessException;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 基于redisson实现黑名单机制
 */
@Service
public class BlackListService {

    private static final String BLACKLIST_KEY = "blacklist"; // 黑名单的 Redis 键
    
    @Resource
    private RedissonClient redissonClient;

    // 添加用户到黑名单
    public void addToBlacklist(Long userIdentifier) {
        //用户恶意进行调用，进入黑名单
        RList<Long> blackList = redissonClient.getList(BLACKLIST_KEY);
        blackList.add(userIdentifier);
    }

    // 检查用户是否在黑名单
    public boolean isUserInBlacklist(Long userIdentifier) {
        RList<Long> blackList = redissonClient.getList(BLACKLIST_KEY);
        return blackList.contains(userIdentifier);
    }

    // 获取黑名单
    public List<Long> getBlackList(){
        RList<Long> blackList = redissonClient.getList(BLACKLIST_KEY);
        List<Long> list = new ArrayList<>(blackList);
        return list;
    }

    // 将用户从黑名单中删除
    public boolean delBlackUser(Long userId){
        if(!isUserInBlacklist(userId)){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"该用户不在黑名单中");
        }
        RList<Long> blackList = redissonClient.getList(BLACKLIST_KEY);
        boolean remove = blackList.remove(userId);
        return remove;
    }

}